import Vue from "vue";
import axios from "axios";
import store from "../store";
import router from "../router";
import { getUserToken, removeUserInfo, removeUserToken } from "./auth";

// 创建axios实例
const request = axios.create({
  // baseURL: "/dev",
  timeout: 5000,
});

// loading加载效果
const loading = {
  // 加载中...
  open: function() {
    Vue.prototype.$Spin.show({
      render: (h) => {
        return h("div", [
          h("Icon", {
            class: "demo-spin-icon-load",
            props: {
              type: "ios-loading",
              size: 18,
            },
          }),
          h("div", "加载中..."),
        ]);
      },
    });
  },
  // 关闭
  close: function() {
    Vue.prototype.$Spin.hide();
  },
};

// 箭头函数写法会出 bug, 错误请求和错误响应不会执行其中的代码, 故换成普通函数
// 添加请求拦截器
request.interceptors.request.use(
  function(config) {
    if (config.url !== "/login") {
      config.headers.token = getUserToken();
    }
    loading.open();
    return config;
  },
  function(error) {
    loading.close();
    return Promise.reject(error);
  }
);
// 添加响应拦截器
request.interceptors.response.use(
  function(response) {
    loading.close();
    return response;
  },
  function(error) {
    loading.close();
    if (error.response.status == 400) {
      Vue.prototype.$Message.error("登录超时");
      store.dispatch("loginOut");
      removeUserInfo();
      removeUserToken();
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default request;
